import CustomHook from 'spa-custom-hooks';
import { request } from "./request/index.js"
import { getShareInfo, login, showToast } from "./utils/asyncWx.js"
let globalData = {
  // 是否已经拿到shareTicket
  shareTicket: '',
  // 是否已经拿到opengid
  opengid: '',
  // 是否已经拿到eventid
  eventid: '',
  // 是否已经拿到token
  token: ''
}
CustomHook.install({
  'User': {
    name: 'User',
    watchKey: 'token',
    onUpdate(val) {
      // token非空则触发此钩子
      return !!val
    }
  }
}, globalData || 'globalData')
App({
  onLaunch: async function () {

    console.log("onLaunch is triggered!")

    // 前端登录
    let { code } = await login();
    // 后端登录
    const res = await request({ url: "/WxUser/login", data: { code } });
    // 保存openid
    // let openid = res.data.data.openid
    // this.globalData.openid = openid
    // wx.setStorageSync('openid', openid)

    // 保存token
    let token = res.data.data.token
    this.globalData.token = token
    wx.setStorageSync('token', token)

  },
  onShow: function (options) {
    console.log("App onShow's options:>>>>>> ",options) // TEST
    let that = this
    if (options && options.scene == 1044) {
      that.globalData.shareTicket = options.shareTicket
    }
    this.globalData.eventid = options.query.eventid
    console.log('onShow---options=--->', options)
  },
  async getShareTicket(cb) {
    try {
      if (this.globalData.shareTicket) {
        let res = await getShareInfo(this.globalData.shareTicket)
        console.log('getShareTicket---shareTicket-->', res)
        // 得到opengid的加密数据
        let encryptedData = res.encryptedData
        let iv = res.iv
        // 获取token
        let token = wx.getStorageSync('token')
        if (token == null) {
          // 前端登录
          let { code } = await login();
          // 后端登录
          res = await request({ url: "/WxUser/login", data: { code } });
          // 保存openid
          // tooken = res.data.data.openid

          // 保存token
          let token = res.data.data.token
          this.globalData.token = token
          wx.setStorageSync('token', token)
        }

        this.globalData.token = token
        // token存入缓存
        wx.setStorageSync('token', token)
        // 封POST装头部
        let header = { "Content-Type": "application/x-www-form-urlencoded" }
        // 后端解密
        res = await request({ url: "/WxUser/getDecryptedData", method: "post", data: { encryptedData, iv }, header })
        console.log("解密后的数据：", res);
        // 如果解密失败，提示用户刷新重试
        if (res.statusCode != 200) {
          showToast({ title: "请刷新重试" })
          return
        }
        // 保存opengid
        this.globalData.opengid = res.data.data.openGId
        // 执行调用方的函数，将从后端解密得到的opengid以函数参数形式传给调用方
        typeof cb == "function" && cb(this.globalData)
      } else {
        console.log("不存在shareTicket")
      }
    } catch (err) {
      console.log(err)
    }
  },
  globalData
})
